#include<cstdio>
#include<vector>
using namespace std;
const int maxn=1e5;
struct node{
    int area;
    int data;
    int next;
};

int main(){
    //freopen("in.txt","r",stdin);

    int start,N,K;
    scanf("%d %d %d",&start,&N,&K);
    node inp[maxn];
    vector<node> ngtv;
    vector<node> smlek;
    vector<node> bigek;
    vector<node> k;
    int area,data,next;
    for(int i=0;i<N;i++){
        scanf("%d",&area);
        scanf("%d %d",&inp[area].data,&inp[area].next);
        inp[area].area=area;
    }
    while(start!=-1){
        if(inp[start].data<0){ngtv.push_back(inp[start]);}
        else if(0<=inp[start].data && inp[start].data<=K){smlek.push_back(inp[start]);}
        //else if(inp[start].data==K){k.push_back(inp[start]);}
        else{bigek.push_back(inp[start]);}
        start=inp[start].next;
    }
    vector<node> ans;
    ans.insert(ans.end(),ngtv.begin(),ngtv.end());
    ans.insert(ans.end(),smlek.begin(),smlek.end());
    ans.insert(ans.end(),k.begin(),k.end());
    ans.insert(ans.end(),bigek.begin(),bigek.end());
    int sum=ans.size();
    for(int i=0;i<sum-1;i++){
        printf("%05d %d %05d\n",ans[i].area,ans[i].data,ans[i+1].area);
    }
    printf("%05d %d -1\n",ans[sum-1].area,ans[sum-1].data);
}
